package edu.hawaii.duedates;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * This is an application that retrieves the user's information 
 * in borrowing items at UH Manoa Library.
 * 
 * @author John Ancheta, Daniel Arakaki, Mari-Lee Flestado
 *
 */
public class UniversityOfHawaiiLibrary {
  /**
   * Attempts to login to UH Manoa Library system.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * 
   * @return The WebConversation instance after successful login.
   * 
   * @throws Exception If login was not successful with these credentials.
   */
  private static WebConversation loginToUhmLibrary(final String id, final String lastName)
      throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    if (id != null && id.length() == 9 && id.charAt(4) == '-') {
      form.setParameter("BC", id.substring(0, 4) + id.substring(5));
    }
    else {
      form.setParameter("BC", id);
    }
    form.setParameter("LN", lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains("Sorry, Login unsuccessful")) {
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }
  
  /**
   * Given a logged in user to the UH Library site, provides info about their library books. Should
   * a user have books checked out, a formatted list will be presented. If no books are borrowed
   * then a message will be displayed.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @param bookList An array list of due dates and book titles.
   * 
   * @throws Exception If problems occur parsing the site pages.
   */
  public void getUhmInfo(String id, String lastName, List<BookInfoRecord> bookList)
      throws Exception {
    String dateFormat = "MM-dd-yy";
    DateFormat formattedDate = new SimpleDateFormat(dateFormat, Locale.US);
    try {
      WebConversation conversation = loginToUhmLibrary(id, lastName);
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      String uhSiteNoItemString = "You have no items checked out.";
      if (!uhSiteNoItemString.equals(form.getText())) {
        int statusIndex = -1;
        int itemIndex = -1;
        // if the user did not borrow anything from the library
        WebTable table = response.getTableStartingWith("Status");
        if (table != null) {
          for (int j = 0; j <= table.getColumnCount() - 1; j++) {
            String title = table.getCellAsText(0, j);
            if ("Status".equalsIgnoreCase(title)) {
              statusIndex = j;
            }
            else if ("Item".equalsIgnoreCase(title)) {
              itemIndex = j;
            }
          }
        }
        if (statusIndex >= 0 && itemIndex >= 0) {
          for (int i = 1; i <= table.getRowCount() - 1; i++) {
            String recordDueDate = table.getCellAsText(i, statusIndex);

            if (recordDueDate.length() >= 8) {
              recordDueDate = recordDueDate.substring(recordDueDate.length() - 8);
            }
            String recordBookInfo = table.getCellAsText(i, itemIndex);
            Date aDate = formattedDate.parse(recordDueDate);
            bookList.add(new BookInfoRecord(aDate, recordBookInfo, "uhm"));
          }
        }
      }
    }
    catch (Exception e) {
      throw new Exception("Unable to get UH Book info:\n  ", e);
    }
  }

}
